<?php
/**
 * User_Variable
 *
 * Класс для работы с древовидной структурой
 *
 */
class User_Variable{
	/**
	 * получение значений переменных рользователя
	 *
	 * @param array|int $arrUserIDs - массив или один ID_user
	 * @param array|string $arrValuesName - массив или одно valueName
	 */
/*	public static function getVariableValue(array $arrUserIDs, array $arrValuesName){
		if (!is_array($arrUserIDs) && is_int($arrUserIDs))
			$arrUserIDs[0] = $arrUserIDs;
		if (!is_array($arrValuesName) && is_string($arrValuesName))
			$arrValuesName[0] = $arrValuesName;
		$objDB = Service_Database::instance();
		print_r($arrUserIDs);print_r($arrValuesName);
		if (sizeof($arrUserIDs) != 0){
			if (sizeof($arrValuesName) != 0){
				$stmt = 'SELECT `user_variable`.`variable_value`
						 FROM `user_variable`
						 WHERE `user_variable`.`ID_user` = IN ("' . join('", "', $arrUserIDs) . '")
						 AND `user_variable`.`variable_name` = IN ("' . join('", "', $arrUserIDs) . '")';
				return $objDB->selectSimpleArray($stmt);
			} else return false;
		} else return false;
	}*/
	/**
	 * получение значения переменной/переменных пользователя
	 *
	 * @param int $idUser
	 * @param string|array $variableName - название перменной / массив названий
	 * @param bool $simpleArray - тип возвращаемого массива
	 * @return array
	 */
	public static function getVariableValue($idUser, $variableName, $simpleArray = false){
		$objDB = Service_Database::instance();
		$objSession = User_Session::instance();
		if (is_array($variableName)){
			$varSize = sizeof($variableName);
			$arrReturn = array();
			$i=0;
			$defVal = 0;
			$arrVarName = array('tagsCloudMinimizedFlag', 'userMenuMinimizedFlag', 'tagsFavsMinimizedFlag','siteAbilitiesMinimizedFlag', 'loginMinimizedFlag', 'mainMenuMinimizedFlag', 'tutorialThemeMenuMinimizedFlag',
			'solutionFilter', 'articleFilter'); // для только что пришедшего пользователя
			if ($variableName == $arrVarName and !$idUser)
				$defVal = 1;
			foreach ($variableName as $name){
				$arrReturn[$i]['variable_name'] = $name;
				$arrReturn[$i]['variable_value'] = $defVal;
				switch ($name){
					case 'solutionFilter': $arrReturn[$i]['variable_value'] = 1; break;
					case 'articleFilter': $arrReturn[$i]['variable_value'] = 0; break;
					case 'tagsCloudMinimizedFlag': $arrReturn[$i]['variable_value'] = 1; break;
					case 'siteAbilitiesMinimizedFlag': $arrReturn[$i]['variable_value'] = 1; break;
				}
				$i++;
			}

			if ($idUser){
				$stmtWhat = 'SELECT `user_variable`.`variable_value`, `user_variable`.`variable_name` ';
				$stmtWhere = ' AND `user_variable`.`variable_name` IN ("' . join('", "', $variableName) . '")';
				$stmt = $stmtWhat . 'FROM `user_variable` WHERE `user_variable`.`ID_user` = ' . $idUser . $stmtWhere;
				$arrNotSimple = $objDB->select($stmt);

			}
			else {
				$arrTemp = $objSession->__getArray(); // result in simple array
				$arrNotSimple = array();
				$i = 0;
				if ($arrTemp)
					foreach ($arrTemp as $varName=>$varValue){
						$arrNotSimple[$i]['variable_name'] = $varName;
						$arrNotSimple[$i]['variable_value'] = $varValue;
						$i++;
					}
			}

			$selectSize = sizeof($arrNotSimple);
			for ($i = 0; $i < $varSize; $i++){
				for ($j=0; $j<$selectSize; $j++){
					if ($arrNotSimple[$j]['variable_name'] == $arrReturn[$i]['variable_name'])
						$arrReturn[$i]['variable_value'] = $arrNotSimple[$j]['variable_value'];
				}
			}
			if (!$simpleArray)
				return $arrReturn;
			else {
				$arrResult = array();
				for($i = 0; $i < $varSize; $i++)
					$arrResult[$arrReturn[$i]['variable_name']] = $arrReturn[$i]['variable_value'];
				return $arrResult;
			}
		}else
		{
			if ($idUser){
				$stmtWhere = ' AND `user_variable`.`variable_name` = "' . $variableName . '"';
				$stmtWhat = 'SELECT `user_variable`.`variable_value`';
				$stmt = $stmtWhat . 'FROM `user_variable` WHERE `user_variable`.`ID_user` = ' . $idUser . $stmtWhere;
				return $objDB->selectSimpleField($stmt);
			}
			else {
				return $objSession->__get($variableName);
			}
		}
















			/*$size = sizeof($variableName);



		if ($idUser){
				$stmt = $stmtWhat . 'FROM `user_variable`
						 WHERE `user_variable`.`ID_user` = ' . $idUser . $stmtWhere;
				if (is_array($variableName)){
					$arrSelect = $objDB->select($stmt);
					$arrTemp = array();
					$selectSize = sizeof($arrSelect);
					if ($selectSize < $size){
						for ($i = 0; $i<$size; $i++){
							for ($j = 0; $j<$selectSize; $j++){
								if(isset($arrSelect[$j]['variable_name']) && $arrSelect[$j]['variable_name'] == $variableName[$i]){
									$arrTemp[$i]['variable_name'] = $variableName[$i];
									$arrTemp[$i]['variable_value'] = $arrSelect[$j]['variable_value'];
								}
								elseif (!isset($arrTemp[$i]['variable_value']) || (isset($arrTemp[$i]['variable_value']) && $arrTemp[$i]['variable_value'] == NULL)) {
									$arrTemp[$i]['variable_name'] = $variableName[$i];
									$arrTemp[$i]['variable_value'] = 0;
								}
							}
						}


						if ($selectSize == 0){
							$arrTemp = array();
							for ($i = 0; $i < $size; $i++){
								$arrTemp[$i]['variable_name'] = $variableName[$i];
								$arrTemp[$i]['variable_value'] = 0;

							}
						}
				}
				else $arrTemp = $arrSelect;


							//echo '<pre>';
							//print_r($arrTemp);
							//echo '</pre>';


					if (!$simpleArray)
      					return $arrTemp;
     				else {
     					$arrReturn = array();
      					for ($i=0; $i<$size; $i++)
      						 $arrReturn[$arrTemp[$i]['variable_name']] = $arrTemp[$i]['variable_value'];
      					return $arrReturn;
     					}
				}
				else
					return $objDB->selectSimpleField($stmt);
		}
		else {
			$objSession = User_Session::instance();
			if (is_array($variableName)){
				$arrTemp = $objSession->__getArray();
				$arrResult = array();
				for ($i=0; $i<$size; $i++){
					$arrResult[$variableName[$i]] = isset($arrTemp[$variableName[$i]]) ?  $arrTemp[$variableName[$i]] : NULL;
				}
				if ($simpleArray)
					return $arrResult;
				else {
					$i = 0;
					$arrReturn = array();
					if (sizeof($arrResult) > 0)
						foreach ($arrResult as $key => $value){
							$arrReturn[$i]['variable_name'] = $key;
							$arrReturn[$i]['variable_value'] = $value;
							$i++;
						}
					return $arrReturn;
				}
			}
			return $objSession->__get($variableName);
		}
*/
	}

	public static function addVariableValue($idUser, $variableName, $variableValue){
		$objDB = Service_Database::instance();
/*		if (is_array($variableName)){
			foreach ($variableName as $name){
				$arrTempName[$i] = $name;
				$i++;
			}
			$variableName = $arrTempName;
		}
		else {
			$variableName = array(0=>$variableName);
			$variableValue = array(0=>$variableValue);
		}*/
		if (!self::checkVariable($variableName))
			return false;

		if (is_array($variableValue) && is_array($variableName)){
			$arrVarNameSize = sizeof($variableName);
			$arrVarValueSize = sizeof($variableValue);
			if ($arrVarNameSize == $arrVarValueSize){
				for($i=0; $i < $arrVarNameSize; $i++){
					self::addVariableValue($idUser, $variableName[$i], $variableValue[$i]);
				}
				return true;
			}
			return false;
		}
		if ($idUser){
			if ($objDB->isRecordExist('SELECT `user_variable`.`variable_value` FROM `user_variable` WHERE `user_variable`.`ID_user` = ' . $idUser . ' AND `user_variable`.`variable_name` = "' . $variableName . '"')){
				$arrUpdate = array('variable_value' => $variableValue);
				$arrWhere = array('ID_user' => $idUser, 'variable_name' => $variableName);
				$objDB->update('user_variable', $arrUpdate, $arrWhere);
			}
			else {
				$arrInsert = array('ID_user' => $idUser, 'variable_name' => $variableName, 'variable_value' => $variableValue);
				$objDB->insert('user_variable', $arrInsert);
			}
			return true;
		}
		else {
		if (is_array($variableValue) && is_array($variableName)){
			$arrVarNameSize = sizeof($variableName);
			$arrVarValueSize = sizeof($variableValue);
			if ($arrVarNameSize == $arrVarValueSize){
				$arrAdd = array();
				for($i=0; $i < $arrVarNameSize; $i++){
					$arrAdd[$variableName[$i]] = $variableValue[$i];
				}
				$objSession->__setArray($arrAdd);
				return true;
			}
			return false;
		}
			$objSession = User_Session::instance();
			$objSession->__set($variableName, $variableValue);
			return true;
		}
		return false;
	}

	public static function checkVariable($variableName){
		if (!is_array($variableName))
			$variableName = array(0=>$variableName);
		foreach ($variableName as $varName){
			switch ($varName){
				case "tree_structure_linear_flag" : true; break;
				case "tagsCloudMinimizedFlag" : true; break;
				case "siteAbilitiesMinimizedFlag" : true; break;
				case "userMenuMinimizedFlag" : true; break;
				case "loginMinimizedFlag" : true; break;
				case "minimizeAllCommentsBranch" : true; break;
				case "mainMenuMinimizedFlag": true; break;
				case "tagsFavsMinimizedFlag": true; break;
				case "showAllTutorialComplex": true; break;
				case "articleShow" : true; break;
				case "articleFilter" : true; break;
				case "articleFilterStartDate" : true; break;
				case "articleFilterEndDate" : true; break;
				case "articleFilterRating" : true; break;
				case "articleFilterComplexity" : true; break;
				case "articleFilterSort" : true; break;
				case "articleFilterDirection" : true; break;
				case "articleFilterLikeFolder" : true; break;
				case "articleFilterFolder" : true; break;
				case "folderarticleFilter" : true; break;
				case "folderarticleFilterStartDate" : true; break;
				case "folderarticleFilterEndDate" : true; break;
				case "folderarticleFilterRating" : true; break;
				case "folderarticleFilterComplexity" : true; break;
				case "folderarticleFilterSort" : true; break;
				case "folderarticleFilterDirection" : true; break;
				case "folderarticleFilterLikeFolder" : true; break;
				case "folderarticleFilterFolder" : true; break;
				case "questionFilter" : true; break;
				case "questionFilterStartDate" : true; break;
				case "questionFilterEndDate" : true; break;
				case "questionFilterRating" : true; break;
				case "questionFilterSort" : true; break;
				case "questionFilterDirection" : true; break;
				case "tutorialFilter" : true; break;
				case "tutorialFilterStartDate" : true; break;
				case "tutorialFilterEndDate" : true; break;
				case "tutorialFilterSort" : true; break;
				case "tutorialFilterDirection" : true; break;
				case "solutionFilter" : true; break;
				case "solutionFilterStartDate" : true; break;
				case "solutionFilterEndDate" : true; break;
				case "solutionFilterRating" : true; break;
				case "solutionFilterSort" : true; break;
				case "solutionFilterDirection" : true; break;
				case "tutorialThemeMenuFlag" : true; break;
				case "tutorialComplexMenuFlag" : true; break;
				case "indexFilterArticle" : true; break;
				case "indexFilterQuestion" : true; break;
				case "indexFilterSolution" : true; break;
				case "indexFilterTutorialLesson" : true; break;
				case "indexFilterCommunity" : true; break;
				case "indexFilterCrequest" : true; break;
				case "indexFilterSize" : true; break;
				default: return false;
			}
		}
		return true;
	}
}
?>